<?php
// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 获取分页参数
$paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$per_page = 20;
$offset = ($paged - 1) * $per_page;

// 获取搜索参数
$search = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
$status_filter = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';

// 构建查询
global $wpdb;
$visits_table = $wpdb->prefix . 'spider_visits';
$stats_table = $wpdb->prefix . 'spider_stats';
$where_conditions = array('1=1');
$where_values = array();

if (!empty($search)) {
    $where_conditions[] = "(url LIKE %s OR title LIKE %s OR description LIKE %s)";
    $search_term = '%' . $wpdb->esc_like($search) . '%';
    $where_values = array_merge($where_values, array($search_term, $search_term, $search_term));
}

if (!empty($status_filter)) {
    if ($status_filter === 'success') {
        $where_conditions[] = "status_code >= 200 AND status_code < 300";
    } elseif ($status_filter === 'error') {
        $where_conditions[] = "status_code >= 400";
    } elseif ($status_filter === 'redirect') {
        $where_conditions[] = "status_code >= 300 AND status_code < 400";
    }
}

$where_clause = implode(' AND ', $where_conditions);

// 获取总数
$count_query = "SELECT COUNT(*) FROM $table_name WHERE $where_clause";
if (!empty($where_values)) {
    $total_items = $wpdb->get_var($wpdb->prepare($count_query, $where_values));
} else {
    $total_items = $wpdb->get_var($count_query);
}

$total_pages = ceil($total_items / $per_page);

// 获取结果
$query = "SELECT * FROM $table_name WHERE $where_clause ORDER BY last_analyzed DESC LIMIT %d OFFSET %d";
$where_values[] = $per_page;
$where_values[] = $offset;

if (!empty($where_values)) {
    $results = $wpdb->get_results($wpdb->prepare($query, $where_values), ARRAY_A);
} else {
    $results = $wpdb->get_results($wpdb->prepare($query, $per_page, $offset), ARRAY_A);
}

// 统计信息
$stats = $wpdb->get_row("
    SELECT 
        COUNT(*) as total_urls,
        AVG(response_time) as avg_response_time,
        AVG(word_count) as avg_word_count,
        SUM(CASE WHEN status_code >= 200 AND status_code < 300 THEN 1 ELSE 0 END) as success_count,
        SUM(CASE WHEN status_code >= 400 THEN 1 ELSE 0 END) as error_count,
        SUM(CASE WHEN mobile_friendly = 1 THEN 1 ELSE 0 END) as mobile_friendly_count,
        SUM(CASE WHEN ssl_enabled = 1 THEN 1 ELSE 0 END) as ssl_enabled_count
    FROM $table_name
", ARRAY_A);
?>

<div class="wrap">
    <h1>分析结果</h1>
    
    <!-- 统计信息 -->
    <div class="wp-url-spider-stats">
        <div class="stat-card">
            <div class="stat-number"><?php echo number_format($stats['total_urls']); ?></div>
            <div class="stat-label">总URL数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo number_format($stats['success_count']); ?></div>
            <div class="stat-label">成功页面</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo number_format($stats['error_count']); ?></div>
            <div class="stat-label">错误页面</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo round($stats['avg_response_time'], 2); ?>s</div>
            <div class="stat-label">平均响应时间</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo number_format($stats['mobile_friendly_count']); ?></div>
            <div class="stat-label">移动端友好</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo number_format($stats['ssl_enabled_count']); ?></div>
            <div class="stat-label">SSL启用</div>
        </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="wp-url-spider-filters">
        <form method="get" action="">
            <input type="hidden" name="page" value="wp-url-spider-results">
            
            <div class="filter-row">
                <div class="filter-group">
                    <label for="search-input">搜索：</label>
                    <input type="text" id="search-input" name="s" value="<?php echo esc_attr($search); ?>" 
                           placeholder="搜索URL、标题或描述...">
                </div>
                
                <div class="filter-group">
                    <label for="status-filter">状态：</label>
                    <select id="status-filter" name="status">
                        <option value="">全部状态</option>
                        <option value="success" <?php selected($status_filter, 'success'); ?>>成功 (2xx)</option>
                        <option value="redirect" <?php selected($status_filter, 'redirect'); ?>>重定向 (3xx)</option>
                        <option value="error" <?php selected($status_filter, 'error'); ?>>错误 (4xx+)</option>
                    </select>
                </div>
                
                <div class="filter-actions">
                    <button type="submit" class="button">筛选</button>
                    <a href="?page=wp-url-spider-results" class="button">清除</a>
                </div>
            </div>
        </form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="wp-url-spider-actions">
        <button type="button" class="button" id="export-csv">
            <span class="dashicons dashicons-download"></span> 导出CSV
        </button>
        <button type="button" class="button" id="export-json">
            <span class="dashicons dashicons-download"></span> 导出JSON
        </button>
        <button type="button" class="button" id="delete-selected" style="color: #a00;">
            <span class="dashicons dashicons-trash"></span> 删除选中
        </button>
    </div>
    
    <!-- 结果表格 -->
    <div class="wp-url-spider-table-container">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <td class="manage-column column-cb check-column">
                        <input type="checkbox" id="select-all">
                    </td>
                    <th class="manage-column column-url">URL</th>
                    <th class="manage-column column-title">标题</th>
                    <th class="manage-column column-status">状态</th>
                    <th class="manage-column column-response-time">响应时间</th>
                    <th class="manage-column column-word-count">字数</th>
                    <th class="manage-column column-mobile">移动端</th>
                    <th class="manage-column column-ssl">SSL</th>
                    <th class="manage-column column-analyzed">分析时间</th>
                    <th class="manage-column column-actions">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($results)): ?>
                    <tr>
                        <td colspan="10" class="no-items">暂无分析结果</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($results as $result): ?>
                        <tr data-id="<?php echo $result['id']; ?>">
                            <th class="check-column">
                                <input type="checkbox" class="row-checkbox" value="<?php echo $result['id']; ?>">
                            </th>
                            <td class="column-url">
                                <a href="<?php echo esc_url($result['url']); ?>" target="_blank" 
                                   class="url-link" title="<?php echo esc_attr($result['url']); ?>">
                                    <?php echo esc_html(wp_trim_words($result['url'], 8)); ?>
                                </a>
                            </td>
                            <td class="column-title">
                                <?php if (!empty($result['title'])): ?>
                                    <span title="<?php echo esc_attr($result['title']); ?>">
                                        <?php echo esc_html(wp_trim_words($result['title'], 6)); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="no-data">无标题</span>
                                <?php endif; ?>
                            </td>
                            <td class="column-status">
                                <span class="status-code status-<?php echo substr($result['status_code'], 0, 1); ?>xx">
                                    <?php echo $result['status_code']; ?>
                                </span>
                            </td>
                            <td class="column-response-time">
                                <?php echo $result['response_time']; ?>s
                            </td>
                            <td class="column-word-count">
                                <?php echo number_format($result['word_count']); ?>
                            </td>
                            <td class="column-mobile">
                                <?php if ($result['mobile_friendly']): ?>
                                    <span class="dashicons dashicons-smartphone" title="移动端友好"></span>
                                <?php else: ?>
                                    <span class="dashicons dashicons-no-alt" title="非移动端友好"></span>
                                <?php endif; ?>
                            </td>
                            <td class="column-ssl">
                                <?php if ($result['ssl_enabled']): ?>
                                    <span class="dashicons dashicons-lock" title="SSL启用"></span>
                                <?php else: ?>
                                    <span class="dashicons dashicons-unlock" title="SSL未启用"></span>
                                <?php endif; ?>
                            </td>
                            <td class="column-analyzed">
                                <?php echo date('Y-m-d H:i', strtotime($result['last_analyzed'])); ?>
                            </td>
                            <td class="column-actions">
                                <button type="button" class="button button-small view-details" 
                                        data-id="<?php echo $result['id']; ?>">
                                    查看详情
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total_pages > 1): ?>
        <div class="wp-url-spider-pagination">
            <?php
            $pagination_args = array(
                'base' => add_query_arg('paged', '%#%'),
                'format' => '',
                'prev_text' => '&laquo; 上一页',
                'next_text' => '下一页 &raquo;',
                'total' => $total_pages,
                'current' => $paged,
                'type' => 'plain'
            );
            
            if (!empty($search)) {
                $pagination_args['add_args'] = array('s' => $search);
            }
            if (!empty($status_filter)) {
                $pagination_args['add_args']['status'] = $status_filter;
            }
            
            echo paginate_links($pagination_args);
            ?>
        </div>
    <?php endif; ?>
</div>

<!-- 详情模态框 -->
<div id="details-modal" class="wp-url-spider-modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h2>分析详情</h2>
            <span class="close">&times;</span>
        </div>
        <div class="modal-body" id="details-content">
            <!-- 详情内容将通过JavaScript加载 -->
        </div>
    </div>
</div>

<style>
.wp-url-spider-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin: 20px 0;
}

.stat-card {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    text-align: center;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
}

.stat-number {
    font-size: 2em;
    font-weight: bold;
    color: #0073aa;
    margin-bottom: 5px;
}

.stat-label {
    color: #666;
    font-size: 14px;
}

.wp-url-spider-filters {
    background: #fff;
    border: 1px solid #e1e5e9;
    border-radius: 12px;
    padding: 24px;
    margin: 20px 0;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.filter-row {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    align-items: end;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-width: 0;
}

.filter-group label {
    font-size: 13px;
    font-weight: 600;
    color: #50575e;
    margin-bottom: 2px;
}

.filter-group input,
.filter-group select {
    padding: 10px 12px;
    border: 1px solid #8c8f94;
    border-radius: 4px;
    font-size: 14px;
    width: 100%;
    box-sizing: border-box;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.filter-group input:focus,
.filter-group select:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 1px #007cba;
}

.filter-group input:hover,
.filter-group select:hover {
    border-color: #007cba;
}

.filter-actions {
    display: flex;
    gap: 10px;
    align-items: end;
    grid-column: 1 / -1;
    justify-content: flex-start;
}

.wp-url-spider-actions {
    margin: 20px 0;
    display: flex;
    gap: 10px;
}

.wp-url-spider-table-container {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    overflow: hidden;
}

.wp-url-spider-table-container table {
    margin: 0;
}

.wp-url-spider-table-container th,
.wp-url-spider-table-container td {
    padding: 12px 8px;
    vertical-align: middle;
}

.column-url {
    max-width: 200px;
}

.url-link {
    color: #0073aa;
    text-decoration: none;
    word-break: break-all;
}

.url-link:hover {
    text-decoration: underline;
}

.status-code {
    padding: 4px 8px;
    border-radius: 3px;
    font-weight: bold;
    font-size: 12px;
}

.status-2xx {
    background: #d4edda;
    color: #155724;
}

.status-3xx {
    background: #fff3cd;
    color: #856404;
}

.status-4xx,
.status-5xx {
    background: #f8d7da;
    color: #721c24;
}

.no-data {
    color: #999;
    font-style: italic;
}

.wp-url-spider-pagination {
    margin: 20px 0;
    text-align: center;
}

.wp-url-spider-pagination .page-numbers {
    display: inline-block;
    padding: 8px 12px;
    margin: 0 2px;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-decoration: none;
    color: #0073aa;
}

.wp-url-spider-pagination .page-numbers.current {
    background: #0073aa;
    color: #fff;
    border-color: #0073aa;
}

.wp-url-spider-pagination .page-numbers:hover {
    background: #f1f1f1;
}

/* 模态框样式 */
.wp-url-spider-modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: #fff;
    margin: 5% auto;
    padding: 0;
    border-radius: 4px;
    width: 90%;
    max-width: 800px;
    max-height: 80vh;
    overflow: hidden;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.modal-header {
    background: #f1f1f1;
    padding: 20px;
    border-bottom: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h2 {
    margin: 0;
}

.close {
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.close:hover {
    color: #000;
}

.modal-body {
    padding: 20px;
    max-height: 60vh;
    overflow-y: auto;
}

.detail-section {
    margin-bottom: 20px;
}

.detail-section h3 {
    margin: 0 0 10px 0;
    color: #23282d;
    border-bottom: 1px solid #eee;
    padding-bottom: 5px;
}

.detail-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 10px;
}

.detail-item {
    background: #f9f9f9;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #ddd;
}

.detail-label {
    font-weight: bold;
    color: #666;
    font-size: 12px;
    text-transform: uppercase;
    margin-bottom: 5px;
}

.detail-value {
    color: #23282d;
    word-break: break-word;
}

@media (max-width: 1200px) {
    .filter-row {
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
        gap: 15px;
    }
}

@media (max-width: 960px) {
    .filter-row {
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 12px;
    }
    
    .wp-url-spider-filters {
        padding: 20px;
    }
}

@media (max-width: 768px) {
    .filter-row {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .filter-actions {
        grid-column: 1;
        margin-top: 10px;
    }
    
    .wp-url-spider-filters {
        padding: 15px;
        border-radius: 8px;
    }
    
    .filter-group input,
    .filter-group select {
        min-width: auto;
        width: 100%;
    }
    
    .wp-url-spider-table-container {
        overflow-x: auto;
    }
    
    .modal-content {
        width: 95%;
        margin: 2% auto;
    }
    
    .detail-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 480px) {
    .filter-row {
        gap: 12px;
    }
    
    .filter-group label {
        font-size: 12px;
    }
    
    .filter-group input,
    .filter-group select {
        padding: 8px 10px;
        font-size: 13px;
    }
    
    .filter-actions {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-actions button {
        width: 100%;
    }
    
    .wp-url-spider-filters {
        padding: 12px;
    }
}
</style>
